package com.web.frame.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HandlerInterceptor implements org.springframework.web.servlet.HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(HandlerInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String session = null;
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                session = cookie.getName();
            }
        }
        if ("SUCCESS".equals(session)) {
            logger.info("用户已登录访问content目录");
            return true;
        }else {
            request.getRequestDispatcher("/login").forward(request,response);
            return false;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        logger.info("已执行拦截器的postHandle方法");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        logger.info("已执行拦截器的afterCompletion方法");
    }
}
